package rocket.users;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import rocket.database.DatabaseController;
import rocket.medical.Treatment;
import rocket.server.Access;
/**
 * 
 * @author justin
 * @version
 *
 */
public abstract class User {

	// TODO Make regex's for the following information

	// Server Information
	public abstract Access getAccess();

	public abstract Long getID();

	public abstract void setID(long id);

	public abstract void setConnection(Connection con);

	// Personal Information
	public abstract String name();

	public abstract String birthDate();

	public abstract String gender();

	public abstract String phone();

	public abstract String city();

	public abstract String region();

	// Medical Information
	public abstract String pharmacy();

	public abstract String insurance();

	public abstract List<Treatment> record();

	public abstract List<Treatment> record(String date);

	public abstract List<Treatment> record(String startDate, String endDate);

	public abstract void writeLog(String s);
	
	// Non-Abstract Methods
	/**
	 * Gets the grants for the given user's access level
	 * 
	 * @return a string representing grants for this user's current access level
	 */
	public String grants() {
		return this.getAccess().grants();
	}

	/**
	 * Attempts to login to the database using a username and password
	 * 
	 * @param user
	 * @param password
	 * @return
	 */
	public boolean login(String user, String password) {
		DatabaseController dbc = DatabaseController.getDBC();
		int attempt = dbc.getLoginAttempt(getID(user));
		boolean connected = false;
		if (attempt < 3) {
			try {
				Connection con = dbc.connect(user, password);
				setConnection(con);
				dbc.resetLoginAttempts(getID(user));
				connected = true;
			} catch (SQLException e) {
				dbc.setLoginAttempts(getID(user),
						attempt + 1);
			}
		} else {

		}
		return connected;
	}
	
	/**
	 * Logs out of the system by setting the connection to null
	 * 
	 * @return true for successful logout
	 */
	public boolean logout() {
		setConnection(null);
		return true;
	}

	/**
	 * Gets the current login attempts for this user
	 * 
	 * @return the login attempts for this user
	 */
	public int getLoginAttempts() {
		DatabaseController dbc = DatabaseController.getDBC();
		return dbc.getLoginAttempt(getID());
	}

	/**
	 * Returns the username of this user
	 * 
	 * @return the username of this user
	 */
	public String username() {
		return name().charAt(0) + "" + getID();
	}

	/**
	 * Gets the userID of a user with a given username
	 * 
	 * @param username
	 *            the username of a user
	 * @return the id of a user with the username
	 */
	public long getID(String username) {
		return Long.parseLong(username.substring(1));
	}
}
